<template>
  <div class="flex items-center justify-center" w="360px">
    <Form
      class="w-full"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      :model="formState"
      :rules="rules"
      ref="formRef"
      autocomplete="off"
      @finish="onMatch"
    >
      <FormItem label="城市" name="cityCode">
        <Select
          v-model:value="formState.cityCode"
          class="w-full"
          placeholder="请选择热门城市"
          :getPopupContainer="triggerNode => triggerNode.parentNode"
        >
          <SelectOption
            v-for="(item, index) in cityOptions"
            :value="item.id"
            :label="item.name"
            :key="index"
            >{{ item.name }}</SelectOption
          >
        </Select>
      </FormItem>
      <FormItem label="职位分类" name="positionRootCode">
        <Select
          v-model:value="formState.positionRootCode"
          class="w-full"
          placeholder="请选择职位分类"
          show-search
          optionFilterProp="label"
          :getPopupContainer="triggerNode => triggerNode.parentNode"
        >
          <SelectOption
            v-for="(item, index) in hangYeOptions"
            :value="item.code"
            :label="item.name"
            :key="index"
            >{{ item.name }}</SelectOption
          >
        </Select>
      </FormItem>
      <FormItem label="用户姓名" name="name">
        <Input
          v-model:value.trim="formState.name"
          class="w-full"
          placeholder="若简历名称模糊或没有，请补充"
        >
        </Input>
      </FormItem>
      <FormItem label="电话号码" name="phoneNumber">
        <Input
          v-model:value.trim="formState.phoneNumber"
          class="w-full"
          placeholder="如果拿到电话号码，请补充"
        >
        </Input>
      </FormItem>
      <div class="w-full">
        <Button class="w-full" html-type="submit" :loading="loading"
          >启动匹配</Button
        >
      </div>
    </Form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import {
  Button,
  Form,
  FormItem,
  Select,
  SelectOption,
  message,
  notification,
  Input,
} from 'ant-design-vue';
import { sendMessage } from 'webext-bridge';
import { EXT_GET_HANG_YE, EXT_GET_HOT_CITY, EXT_UPLOAD_RESUME } from '~/events';
import { getDomHtml, makeContentLogout } from '~/utils';
import { isValidPhone, isValidPositionName } from '~/utils/reg';

const $emit = defineEmits(['finish']);

const labelCol = { span: 5 },
  wrapperCol = { span: 19 };

const formState = reactive({
  cityCode: undefined,
  positionRootCode: undefined,
  name: '',
  phoneNumber: '',
});

const cityOptions = ref<
  {
    name: string;
    id: string;
  }[]
>([]);

const hangYeOptions = ref<
  {
    name: string;
    code: string;
  }[]
>([]);

const rules = {
  cityCode: [
    {
      required: true,
      trigger: 'change',
      message: '请选择城市',
    },
  ],
  positionRootCode: [
    {
      required: true,
      trigger: 'change',
      message: '请选择职位分类',
    },
  ],
  name: [
    {
      required: false,
      trigger: 'change',
      validator: (rule: any, value: string) => {
        if (!value) {
          return Promise.resolve();
        }
        if (!isValidPositionName(value)) {
          return Promise.reject('支持汉字和字母，区分大小写，最多可填10个汉字');
        } else {
          return Promise.resolve();
        }
      },
    },
  ],
  phoneNumber: [
    {
      required: false,
      trigger: 'change',
      validator: (rule: any, value: string) => {
        if (!value) {
          return Promise.resolve();
        }
        if (!isValidPhone(value)) {
          return Promise.reject('请输入正确的手机号');
        }
        return Promise.resolve();
      },
    },
  ],
};

// const filterOption = (input: string, option: any) => {
//   return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
// };

const loading = ref(false);

async function fetchHotCityList() {
  try {
    const resp = (await sendMessage(EXT_GET_HOT_CITY, {})) as any;
    if (resp.code === 200) {
      cityOptions.value = resp.data;
    } else {
      cityOptions.value = [];
      message.warn(`获取热门城市失败，请刷新重试！`);
    }
  } catch (error) {
    makeContentLogout(error);
  }
}

async function fetchHotHangYeList() {
  try {
    const resp = (await sendMessage(EXT_GET_HANG_YE, {})) as any;
    if (resp.code === 200) {
      hangYeOptions.value = resp.data;
    } else {
      hangYeOptions.value = [];
      message.warn(`获取职位分类失败，请刷新重试！`);
    }
  } catch (error) {
    makeContentLogout(error);
  }
}

fetchHotCityList();
fetchHotHangYeList();
onLiePin();

async function onMatch() {
  loading.value = true;
  const resp = await getDomHtml(window.location.hostname);
  if (!resp) {
    loading.value = false;
    return;
  }
  const { platform, html, hashId, pdfHtml } = resp;
  const params = { ...formState, html, platform, hashId, pdfHtml };
  try {
    const resp = (await sendMessage(EXT_UPLOAD_RESUME, params)) as any;
    if (resp.code === 200) {
      setTimeout(() => {
        $emit('finish', resp.data);
        loading.value = false;
        notification.info({
          message: '小点提示',
          description: '添加成功，请稍后到管理后台查看简历匹配情况。',
        });
      }, 500);
    } else {
      const msg = resp.msg;
      notification.error({
        message: '小点提示',
        description: msg,
      });
      setTimeout(() => {
        loading.value = false;
      }, 500);
    }
  } catch (error) {
    makeContentLogout(error);
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
}

// 修改猎聘的网页
function onLiePin() {
  if (window.location.href.indexOf('liepin') > -1) {
    const html = document.querySelector('.basic-cont .sep-info');
    const text = html?.firstChild?.nodeValue;
    let _text: string;
    if (text === '女') {
      _text = '女士';
    } else {
      _text = '先生';
    }

    const nameBox = document.querySelector('.basic-cont h4');
    if (nameBox && nameBox.innerHTML.indexOf('**') > -1) {
      nameBox.innerHTML = nameBox?.innerHTML.replaceAll('**', _text);
    }
  }
}
</script>
